package negocio.daos;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import negocio.entidades.Disciplina;
import negocio.entidades.Usuario;

public class DisciplinaDAO {
	private EntityManager em;
	
	public DisciplinaDAO(EntityManager em){
		this.em = em;
	}
	
	public Disciplina salvar(Disciplina d) throws Exception{
		if (d.getId() > 0){
			if (consultarPorId(d.getId()) != null){
				em.merge(d);
			}
		}else{
			em.persist(d);
		}
		return d;
	}
	
	public void excluir(long id) throws Exception{
		Disciplina d = consultarPorId(id);
		if (d != null){
				em.remove(d);
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Disciplina> listar(String nome, String semestre) throws Exception{
		Query q = em.createQuery("select d from Disciplina d where d.nome like lower('"+nome+"%') and d.semestre like lower('"+semestre+"%')", Disciplina.class);
		return q.getResultList() ;
	}
	
	public Disciplina consultarPorId(long id) throws Exception{
		Disciplina d = (Disciplina) em.createQuery(
				"select d from Disciplina d where d.id =" + id).getSingleResult();
		return d;
	}

	@SuppressWarnings("unchecked")
	public List<Usuario> listarProfessores() throws Exception{
		Query q = em.createQuery("select u from Usuario u where u.perfil ='PROFESSOR'", Usuario.class);
		return q.getResultList();
	}

	public List<Disciplina> disciplinasProfId(long id,String nome,String semestre) throws Exception{
		Query q = em.createQuery("select distinct d from Disciplina d where d.professor.id ="+id+" and d.nome like lower('"+nome+"%') and d.semestre like lower('"+semestre+"%'))");
		return q.getResultList();
	}
	
	public Disciplina disciplinaProvas(long id) throws Exception{
		Query q = em.createQuery("select d from Disciplina d left join fetch d.provas where d.id ="+id, Disciplina.class);
		return (Disciplina) q.getSingleResult();
	}
	
	public Disciplina disciplinaConteudos(long id) throws Exception{
		Query q = em.createQuery("select d from Disciplina d left join fetch d.conteudos where d.id ="+id, Disciplina.class);
		return (Disciplina) q.getSingleResult();
	}
}
